package org.example.clouddemo.controller.app;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.example.clouddemo.bean.common.entity.Stock;
import org.example.clouddemo.bean.common.param.StockParam;
import org.example.common.annotation.IgnoreAuth;
import org.example.common.api.StockService;
import org.example.common.response.ApiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@Api(tags = "库存接口")
@ApiSupport(order = 2)
@RestController("appStockController")
@RequestMapping("/api/app/stock")
public class StockController {

    @Autowired
    public StockService stockService;

    /**
     * 检查库存
     */
    @ApiOperation(value = "检查库存", notes = "检查指定商品的库存是否充足")
    @ApiOperationSupport(order = 1)
    @PostMapping("check")
    @IgnoreAuth
    public ApiResult checkStock(@Validated @RequestBody StockParam param) {

        boolean hasStock = stockService.checkStock(param.getProductId(), param.getQuantity());
        return ApiResult.success(hasStock);
    }

    /**
     * 扣减库存
     */
    @ApiOperation(value = "扣减库存", notes = "扣减指定商品的库存数量")
    @ApiOperationSupport(order = 2)
    @PostMapping("reduce")
    public ApiResult reduceStock(@Valid @RequestBody StockParam param) {

        try {
            boolean success = stockService.reduceStock(param.getProductId(), param.getQuantity());
            return ApiResult.success(success);
        } catch (Exception e) {

            return ApiResult.error("库存扣减异常: " + e.getMessage());
        }
    }

    @PostMapping("getOne")
    ApiResult<Stock> getOne(@RequestBody StockParam param){
        Stock stock = stockService.getOne(new QueryWrapper<Stock>().eq("product_id", param.getProductId()));
        return ApiResult.success(stock);
    }

    @PostMapping("update")
    ApiResult update(@RequestBody Stock stock){
        return ApiResult.success(stockService.updateById(stock));
    }


}
